<?php

namespace app\index\controller;

use think\Controller;
use think\Db;

class Index extends Controller
{
    protected $api_url = 'http://127.0.0.1:8090';

    public function index()
    {
        $data = input('param.');
//        if (!($data['from_wxid'] == '25112337660@chatroom' ||  $data['event'] == 'EventFriendMsg')) {
//            echo 'noreturn';die;
//        }
        file_put_contents('../runtime/keaimao5.txt', json_encode($data, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);
        $content = trim($data['msg']);
        $pattern = "/^D(\d+)/si";   //d20
        $pattern_config = "/^\x{3002}([\x{4e00}-\x{9fa5}]+)/u";
        $pattern_change = "/^.(.*?)\==/si";
        $res = preg_match($pattern, $content, $match);
        $res_config = preg_match($pattern_config, $content, $match_config);
        $res_change = preg_match($pattern_change, $content, $match_change);
//        var_dump($res_change, $match_change);die;
        $post_data = [];
        $str = '';
        if ($content == '。塔罗单张') {
            $img = "https://api2.qudiao.com/upload/mp/20210518/d76fc201eec847d82a5ffcadb45662b6.jpg";
            $this->post_img($img, $data);
            $str = "愚人是一张代表自发性行为的牌，一段跳脱某种状态的日子，或尽情享受眼前日子的一段时光。对旅游而言，这是一张积极的牌，暗示你将会活在当下，并且会有和生命紧密结合的感觉。“每天都充实，乐趣便在其中”是一句很适合这张牌的古谚语。当你周遭的人都对某事提防戒慎，你却打算去冒这个险时，愚人牌可能就会出现。例如，“噢，我认为现在是换工作的好时机，外面到处都是失业的人哪！”或者“什么！你们俩分开了？你到底在想什么啊？”冒个险！不论如何都要做做看。愚人暗示通往满足之路是经由自发的行动，而长期的计划则是将来的事。";
            if (mb_strlen($str) > 100) {
                $str_arr = $this->mbStrSplit($str, 100);
                foreach ($str_arr as $k => $v) {
                    $this->post_str($v, $data);
                }
            } else {
                //                $str =  $this->cut_str($this->get_dnd_config()[$title], 120);
                $this->post_str($str, $data);
            }
//            $this->post_str("愚人是一张代表自发性行为的牌，一段跳脱某种状态的日子，或尽情享受眼前日子的一段时光。对旅游而言，这是一张积极的牌，暗示你将会活在当下，并且会有和生命紧密结合的感觉。“每天都充实，乐趣便在其中”是一句很适合这张牌的古谚语。当你周遭的人都对某事提防戒慎，你却打算去冒这个险时，愚人牌可能就会出现。例如，“噢，我认为现在是换工作的好时机，外面到处都是失业的人哪！”或者“什么！你们俩分开了？你到底在想什么啊？”冒个险！不论如何都要做做看。愚人暗示通往满足之路是经由自发的行动，而长期的计划则是将来的事。", $data);
        }elseif ($res) {
            $dice_num = $match[1];
            $result = mt_rand(1, $dice_num);
            $str = "{$data['final_from_name']}掷出了{$result}";
            $this->post_str($str, $data);
        } elseif ($res_config) {
            $title = $match_config[1];
            if (!preg_match("/^[\x{4e00}-\x{9fa5}]+/u", $title, $match)) {
                echo 'nochinese';
                die;
            }
            if (!empty($this->get_dnd_config()[$title])) {
                //如果超过100字看来需要分割几次发送
                $str = $this->get_dnd_config()[$title];
                if (mb_strlen($str) > 100) {
                    $str_arr = $this->mbStrSplit($str, 100);
                    foreach ($str_arr as $k => $v) {
                        $this->post_str($v, $data);
                    }
                } else {
                    //                $str =  $this->cut_str($this->get_dnd_config()[$title], 120);
                    $this->post_str($str, $data);
                }
            } else {
                $titles = Db::table('dnd5e_c')->where('title', "like", "%$title%")->column('title');
                $str = "你可能输入错误了，类似的有：\n";
                if (!empty($titles)) {
                    foreach ($titles as $k => $v) {
                        $str .= $v . "\n";
                    }
                    $this->post_str($str, $data);
                }
            }
        } elseif ($res_change) {
            $title = $match_change[1];
            if (!preg_match("/^[\x{4e00}-\x{9fa5}]+/u", $title, $match)) {
                echo 'nochinese';
                die;
            }
            $pos = mb_strpos($content, "==");
            $describle = mb_substr($content, $pos + 2);
            Db::table('dnd5e_c')->insert([
                'title' => $title,
                'describle' => $describle
            ], true);
            cache('dnd_config', null);
            $this->post_str("词条 $title 设置成功了", $data);
        } else {
            $dice_str = $this->dice($content);
            if (!empty($dice_str)) {
                $this->post_str("{$data['final_from_name']}{$dice_str}", $data);
            }
        }
        die;
    }

    public function dice20($str1 = '')
    {
        if ($str1 == "r") {
            $dice = mt_rand(1, 20);
            $str = "你掷出了D20={$dice}";
            if ($dice == 20) {
                $str .= ' 大成功！';
            } elseif ($dice == 1) {
                $str .= ' 大失败！';
            }
            return $str;
        } else {
            return "";
        }

    }

    public function dice_multi($str1 = '')
    {
//        $str1 = '.r3#1d6';
        $pattern = "/^(\x{3002}|\.)r([\d]+)#([\d+D]+)/siu";
        $res = preg_match($pattern, $str1, $match);
        $str = "";
        $str_arr = [];
        if ($res && $match[2] > 0 && $match[2] < 50) {
            for ($i = 1; $i <= (int)$match[2]; $i++) {
                $str_arr[] = $this->dice_normal($match[3]);
            }
        }
        if (!empty($str_arr)) {
            $str = "掷出了{$match[2]}次{$match[3]}" . "\n" . implode("\n", $str_arr) . "\n";
        }
        return $str;
    }

    public function dice_normal($str1 = '')
    {
        $pattern = "/^(\x{3002}|\.)?r?([\d+D]+)/siu";
//        $str1 = "d20+2d6+2";
//        $str2 = ".d20+2d6+2";
        $str = '';
        $res = preg_match($pattern, $str1, $match);
        if ($res) {
            $parse = $match[2];
            $plus_arr = explode('+', $parse);
            $plus_res_arr = [];
            $plus_str = '';
            $plus_str_arr = [];
            if (!empty($plus_arr)) {
                foreach ($plus_arr as $k => $v) {
                    if (!is_numeric($v)) {
                        $times_arr = preg_split("/(D|d)/", $v);
                        if (empty($times_arr[0])) {
                            $times_arr[0] = 1;
                        }
                        $plus_item = [];
                        for ($i=1; $i<=$times_arr[0]; $i++) {
                            $plus_item[] = mt_rand(1, $times_arr[1]);
                        }
                        $plus_res_arr[] = array_sum($plus_item);
                        $plus_str_arr[] = "(" . implode("+", $plus_item) . ")";
                    } else {
                        $plus_res_arr[] = $v;
                        $plus_str_arr[] = $v;
                    }
                }
                if (!empty($plus_res_arr)) {
                    $str = '';
                    $plus_str = implode("+",  $plus_str_arr);
                    $result = array_sum($plus_res_arr);
                    if (count($plus_res_arr) == 1) {
                        $str = "{$result}";
                        if ($str1 == ".rd20" || $str1 == "。rd20") {
                            if ($result == 20) {
                                $str .= " 大成功！";
                            } elseif ($result == 1) {
                                $str .= " 大失败！！";
                            }
                        }
                    } else {
                        $str = "{$plus_str}={$result}";
                    }
                }
            }
        }
        return $str;
    }

    public function dice_2($str1 = '')
    {
        $dice20 = $this->dice20($str1);
        if (!empty($dice20)) {
            return $dice20;
        }

        $dice_multi = $this->dice_multi($str1);
        if (!empty($dice_multi)) {
            return $dice_multi;
        }

        $pattern = "/^(\x{3002}|\.)r?([\d+D]+)/siu";
//        $str1 = "。d20+2d6+2";
//        $str2 = ".d20+2d6+2";
        $str = '';
        $res = preg_match($pattern, $str1, $match);
        if ($res) {
            $parse = $match[2];
            $plus_arr = explode('+', $parse);
            $plus_res_arr = [];
            if (!empty($plus_arr)) {
                foreach ($plus_arr as $k => $v) {
                    if (!is_numeric($v)) {
                        $times_arr = preg_split("/(D|d)/", $v);
                        if (empty($times_arr[0])) {
                            $times_arr[0] = 1;
                        }
                        $plus_res_arr[] = bcmul($times_arr[0], mt_rand(1, $times_arr[1]));
                    } else {
                        $plus_res_arr[] = $v;
                    }
                }
                if (!empty($plus_res_arr)) {
                    $str = '';
                    $plus_str = implode("+", $plus_res_arr);
                    $result = array_sum($plus_res_arr);
                    if (count($plus_res_arr) == 1) {
                        $str = "掷出了{$result}";
                    } else {
                        $str = "掷出了{$plus_str}={$result}";
                    }
                }
            }
        }
        return $str;
    }

    public function dice($str1 = '')
    {
//        $str1 = "。d20+2d6+2";
        $dice20 = $this->dice20($str1);
        if (!empty($dice20)) {
            return $dice20;
        }

        $dice_multi = $this->dice_multi($str1);
        if (!empty($dice_multi)) {
            return $dice_multi;
        }

        $pattern = "/^(\x{3002}|\.)r?([\d+D]+)/siu";
        $str = '';
        $res = preg_match($pattern, $str1, $match);
        if ($res) {
            $parse = $match[2];
            $plus_arr = explode('+', $parse);
            $plus_res_arr = [];
            $plus_str = '';
            $plus_str_arr = [];
            if (!empty($plus_arr)) {
                foreach ($plus_arr as $k => $v) {
                    if (!is_numeric($v)) {
                        $times_arr = preg_split("/(D|d)/", $v);
                        if (empty($times_arr[0])) {
                            $times_arr[0] = 1;
                        }
                        $plus_item = [];
                        for ($i=1; $i<=$times_arr[0]; $i++) {
                            $plus_item[] = mt_rand(1, $times_arr[1]);
                        }
                        $plus_res_arr[] = array_sum($plus_item);
                        $plus_str_arr[] = "(" . implode("+", $plus_item) . ")";
                    } else {
                        $plus_res_arr[] = $v;
                        $plus_str_arr[] = $v;
                    }
                }
                if (!empty($plus_res_arr)) {
                    $str = '';
                    $plus_str = implode("+",  $plus_str_arr);
                    $result = array_sum($plus_res_arr);
                    if (count($plus_res_arr) == 1) {
                        $str = "掷出了{$result}";
                        if ($str1 == ".rd20" || $str1 == "。rd20") {
                            if ($result == 20) {
                                $str .= " 大成功！";
                            } elseif ($result == 1) {
                                $str .= " 大失败！！";
                            }
                        }
                    } else {
                        $str = "掷出了{$plus_str}={$result}";
                    }
                }
            }
        }
        return $str;
    }

    public function post_str($str, $data)
    {
        if ($str != '') {
            if ($data['event'] == 'EventGroupMsg') {
                $post_data['success'] = true;
                $post_data['message'] = "successful!";
                $post_data['event'] = "SendTextMsg";
                $post_data['robot_wxid'] = $data['robot_wxid'];
                $post_data['to_wxid'] = $data['to_wxid'];
                $post_data['member_wxid'] = $data['from_wxid']; //@的人
                $post_data['member_name'] = $data['from_name']; //
                $post_data['group_wxid'] = ""; //
                $post_data['msg'] = $str;
//            $post_data['robot_id'] = $data['robot_id'];
            } elseif ($data['event'] == 'EventFriendMsg') {
                $post_data['success'] = true;
                $post_data['message'] = "successful!";
                $post_data['event'] = "SendTextMsg";
                $post_data['robot_wxid'] = $data['robot_wxid'];
                $post_data['to_wxid'] = $data['to_wxid'];
                $post_data['member_wxid'] = $data['from_wxid']; //@的人
                $post_data['member_name'] = $data['from_name']; //
                $post_data['group_wxid'] = ""; //
                $post_data['msg'] = $str;
            }

            $post_json = json_encode($post_data);
            $res = $this->curl_post_json($this->api_url, $post_json);
            return $res;
        }
    }

    public function post_img($str, $data)
    {
        $img_arr = explode("/", $str);
        if ($str != '') {
            $post_data['success'] = true;
            $post_data['message'] = "successful!";
            $post_data['event'] = "SendImageMsg";
            $post_data['robot_wxid'] = $data['robot_wxid'];
            $post_data['to_wxid'] = $data['to_wxid'];
            $post_data['member_wxid'] = $data['from_wxid']; //@的人
            $post_data['member_name'] = $data['from_name']; //
            $post_data['group_wxid'] = ""; //
            $post_data['msg'] = $str;
            $post_data['msg'] = ['url' => $str, 'name' => $img_arr[count($img_arr) - 1]];

            if ($data['event'] == 'EventGroupMsg') {
            } elseif ($data['event'] == 'EventFriendMsg') {

            }

            $post_json = json_encode($post_data);
            $res = $this->curl_post_json($this->api_url, $post_json);
            return $res;
        }
    }

    public function test_api()
    {
//        $param_json = '{"type":2,"msg_type":1,"function_name":"eventGroupMsg","ip":"http:\/\/127.0.0.1","port":3800,"token":"feiyu","mark":"","charset":0,"robot_id":"wxid_aas9g3ffgfb622","group_id":"wxid_aas9g3ffgfb622","user_id":"wxid_aas9g3ffgfb622","message":".d100","msg_id":"","tag":"","tag2":""}';
        $param_json = '{"event":"EventFriendMsg","robot_wxid":"wxid_aas9g3ffgfb622","robot_name":"","type":1,"from_wxid":"","from_name":"","final_from_wxid":"wxid_aas9g3ffgfb622","final_from_name":"木木","to_wxid":"wxid_aas9g3ffgfb622","msg":"。疗伤"}
';
        $data = json_decode($param_json, true);
//        $data = input('param.');
        if (!($data['from_wxid'] == '25112337660@chatroom' || $data['event'] == 'EventFriendMsg')) {
            echo 'noreturn';
            die;
        }
        file_put_contents('../runtime/keaimao4.txt', json_encode($data, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND);

        $content = $data['msg'];
        $pattern = "/^D(\d+)/si";   //d20
        $pattern_config = "/^\x{3002}([\x{4e00}-\x{9fa5}]+)/u";
        $pattern_change = "/^.(.*?)\==/si";
        $res = preg_match($pattern, $content, $match);
        $res_config = preg_match($pattern_config, $content, $match_config);
        $res_change = preg_match($pattern_change, $content, $match_change);
//        var_dump($res_change, $match_change);die;
        $post_data = [];
        $str = '';
        if ($res) {
            $dice_num = $match[1];
            $result = mt_rand(1, $dice_num);
            $str = "你的骰子结果是{$result}";
            $this->post_str($str, $data);
        } elseif ($res_config) {
            $title = $match_config[1];
            if (!preg_match("/^[\x{4e00}-\x{9fa5}]+/u", $title, $match)) {
                echo 'nochinese';
                die;
            }
            if (!empty($this->get_dnd_config()[$title])) {
                //如果超过100字看来需要分割几次发送
                $str = $this->get_dnd_config()[$title];
                if (mb_strlen($str) > 100) {
                    $str_arr = $this->mbStrSplit($str, 100);
                    foreach ($str_arr as $k => $v) {
                        $this->post_str($v, $data);
                    }
                } else {
                    //                $str =  $this->cut_str($this->get_dnd_config()[$title], 120);
                    $this->post_str($str, $data);
                }
            } else {
                $titles = Db::table('dnd5e_c')->where('title', "like", "%$title%")->column('title');
                $str = "你可能输入错误了，类似的有：\n";
                if (!empty($titles)) {
                    foreach ($titles as $k => $v) {
                        $str .= $v . "\n";
                    }
                    $this->post_str($str, $data);
                }

            }
        } elseif ($res_change) {
            $title = $match_change[1];
            $pos = mb_strpos($content, "==");
            $describle = mb_substr($content, $pos + 2);
            Db::table('dnd5e_c')->insert([
                'title' => $title,
                'describle' => $describle
            ], true);
            cache('dnd_config', null);
            $this->post_str("词条 $title 设置成功了", $data);
        }


        die;
    }

    function get_dnd_config($f5 = 0)
    {
        if (cache('dnd_config') && $f5 == 0) {
            return cache('dnd_config');
        }
        $dnd_config = Db::table('dnd5e_c')->where([])->field('*')->select();
        $list = [];
        foreach ($dnd_config as $k => $v) {
            $list[$v['title']] = $v['describle'];
        }
        cache('dnd_config', $list, 36000);
        return $list;
    }


    function curl_post_json($url, $data_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                "Content-Length: " . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($return_code, $return_content);
    }

    public function curl_post($url, $data = [])
    {
        //初始化
        $curl = curl_init();

//设置url
        curl_setopt($curl, CURLOPT_URL, $url);

// 标识这个请求是一个POST请求
        curl_setopt($curl, CURLOPT_POST, true);

//        $data = ['name'=> "Tom", "age"=> 23];
// http_build_query提交application/x-www-form-urlencoded
// 否则使用multipart/form-data类型
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));

// 不返回HTTP头部信息
        curl_setopt($curl, CURLOPT_HEADER, false);

// 设置获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// 执行命令
        $response = curl_exec($curl);

// 关闭URL请求
        curl_close($curl);

// 显示获得的数据
        return $response;
    }

    function cut_str($sourcestr, $cutlength)
    {
        $returnstr = '';
        $i = 0;
        $n = 0;
        $str_length = strlen($sourcestr);//字符串的字节数
        while (($n < $cutlength) and ($i <= $str_length)) {
            $temp_str = substr($sourcestr, $i, 1);
            $ascnum = Ord($temp_str);//得到字符串中第$i位字符的ascii码
            if ($ascnum >= 224)    //如果ASCII位高与224，
            {
                $returnstr = $returnstr . substr($sourcestr, $i, 3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
                $i = $i + 3;            //实际Byte计为3
                $n++;            //字串长度计1
            } elseif ($ascnum >= 192) //如果ASCII位高与192，
            {
                $returnstr = $returnstr . substr($sourcestr, $i, 2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
                $i = $i + 2;            //实际Byte计为2
                $n++;            //字串长度计1
            } elseif ($ascnum >= 65 && $ascnum <= 90) //如果是大写字母，
            {
                $returnstr = $returnstr . substr($sourcestr, $i, 1);
                $i = $i + 1;            //实际的Byte数仍计1个
                $n++;            //但考虑整体美观，大写字母计成一个高位字符
            } else                //其他情况下，包括小写字母和半角标点符号，
            {
                $returnstr = $returnstr . substr($sourcestr, $i, 1);
                $i = $i + 1;            //实际的Byte数计1个
                $n = $n + 0.5;        //小写字母和半角标点等与半个高位字符宽...
            }
        }
        if ($str_length > $i) {
            $returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
        }
        return $returnstr;
    }

    function mbStrSplit($string, $len = 1)
    {
        $start = 0;
        $strlen = mb_strlen($string);
        while ($strlen) {
            $array[] = mb_substr($string, $start, $len, "utf8");
            $string = mb_substr($string, $len, $strlen, "utf8");
            $strlen = mb_strlen($string);
        }
        return $array;
    }


}
